package com.jnu.student.view;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.jnu.student.R;
import com.jnu.student.data.Bill;
import com.jnu.student.data.BillDataBank;
import com.jnu.student.data.BookItemDetailsActivity;
import com.jnu.student.data.weekRewardDataBank;
import com.jnu.student.data.weekRewardItem;
import com.jnu.student.data.achievementPointDataBank;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;

public class weekRewardFragment extends Fragment implements OnDataChangeListener{
    private double totalScore;
    private double achievementPoint;
    Button button;
    Button donebutton;
    //private dayRewardDataBank dayRewardDataBank;


    private ArrayList<weekRewardItem> weekRewardItems = new ArrayList<>();
    private DayRewardItemAdapter dayRewardItemAdapter;


    public weekRewardFragment() {
        // Required empty public constructor
    }

    public static weekRewardFragment newInstance() {
        weekRewardFragment fragment = new weekRewardFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_week_reward, container, false);

        RecyclerView dayrewardrecyclerView = rootView.findViewById(R.id.recycle_view_week_reward22);
        dayrewardrecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));   //设置布局管理器

        weekRewardItems = new weekRewardDataBank().loadWeekRewardItems(requireActivity());
        totalScore = new weekRewardDataBank().LoadTotalScore(requireActivity());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        dayRewardItemAdapter = new weekRewardFragment.DayRewardItemAdapter(weekRewardItems);
        dayrewardrecyclerView.setAdapter(dayRewardItemAdapter);
        dayRewardItemAdapter.setOnDataChangeListener(this);

        registerForContextMenu(dayrewardrecyclerView);         //注册ContextMenu事件菜单

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);//确保 ItemTouchHelper 已经附加到 RecyclerView 上。
        itemTouchHelper.attachToRecyclerView(dayrewardrecyclerView);
        dayRewardItemAdapter.setItemTouchHelper(itemTouchHelper);

        // 注册用于更新奖励项目的 ActivityResultLauncher
        updataItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 检查返回结果是否成功
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // 获取返回的 Intent 数据
                        Intent data = result.getData();
                        if (data != null) {
                            // 从 Intent 中获取位置、名称和分数
                            int position = data.getIntExtra("position", -1);
                            String name = data.getStringExtra("name");
                            String scoreText = data.getStringExtra("score");

                            // 确保分数文本不为 null，然后将其转换为 double 类型
                            assert scoreText != null;
                            double score = Double.parseDouble(scoreText);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // 加载当前已有的总分数
                            double havedScore = new achievementPointDataBank().loadAchievementPoints(requireContext());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // 检查是否达到添加新奖励项目所需的成就点
                            if (havedScore < score) {
                                // 提示用户成就点不够，需继续努力
                                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                                builder.setMessage("成就点不够哦，继续努力！")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                // 用户点击确定按钮后的处理
                                                dialog.dismiss();
                                            }
                                        });
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            } else {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                havedScore-=score;
                                new achievementPointDataBank().saveAchievementPoints(requireActivity(),havedScore);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                // 获取对应位置的奖励项目，并更新其标题和分数
                                weekRewardItem dayRewardItem = weekRewardItems.get(position);
                                dayRewardItem.setTitle(name);
                                dayRewardItem.setScore(score);

                                // 通知适配器更新指定位置的奖励项目数据
                                dayRewardItemAdapter.notifyItemChanged(position);

                                // 保存更新后的奖励项目数据到本地数据存储
                                new weekRewardDataBank().SaveWeekRewardItems(requireActivity(), weekRewardItems);
                            }
                        }
                    }
                });

        // 注册用于添加新奖励项目的 ActivityResultLauncher
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 检查返回结果是否成功
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // 获取返回的 Intent 数据
                        Intent data = result.getData();
                        if (data != null) {
                            // 从 Intent 中获取名称和分数
                            String name = data.getStringExtra("name");
                            String scoreText = data.getStringExtra("score");

                            // 确保分数文本不为 null，然后将其转换为 double 类型
                            assert scoreText != null;
                            double score = Double.parseDouble(scoreText);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // 加载当前已有的总分数
                            double havedScore = new achievementPointDataBank().loadAchievementPoints(requireContext());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // 检查是否达到添加新奖励项目所需的成就点
                            if (havedScore < score) {
                                // 提示用户成就点不够，需继续努力
                                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                                builder.setMessage("成就点不够哦，继续努力！")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                // 用户点击确定按钮后的处理
                                                dialog.dismiss();
                                            }
                                        });
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            } else {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                havedScore-=score;
                                new achievementPointDataBank().saveAchievementPoints(requireActivity(),havedScore);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                // 成就点充足，添加新的奖励项目
                                weekRewardItems.add(new weekRewardItem(name, score));

                                // 刷新适配器以插入新的奖励项目，并保存数据到本地数据存储
                                dayRewardItemAdapter.notifyItemInserted(weekRewardItems.size());
                                new weekRewardDataBank().SaveWeekRewardItems(requireActivity(), weekRewardItems);
                            }
                        }
                    }
                    // 处理取消操作
                });

        button = rootView.findViewById(R.id.button_add22);

        donebutton = rootView.findViewById(R.id.button_done22);
        boolean isAtLeastOneChecked = false;
        for (weekRewardItem d : weekRewardItems) {
            if (d.isSelected()) {
                isAtLeastOneChecked = true;
                break;
            }
        }
        // 根据是否有条目被选中来显示或隐藏按钮
        donebutton.setVisibility(isAtLeastOneChecked ? View.VISIBLE : View.GONE);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件的逻辑
                Intent intent = new Intent(requireActivity(), BookItemDetailsActivity.class);
                addItemLauncher.launch(intent);
            }
        });


        donebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("确认完成");
                builder.setMessage("确认都完成了吗？");
                // 设置确认按钮的点击事件
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 创建一个新的账单对象，并获取当前日期
                        ArrayList<Bill> bills = new BillDataBank().loadBills(requireActivity());
                        LocalDate currentDate = LocalDate.now();

                        for (weekRewardItem item : weekRewardItems) {
                            if (item.isSelected()) {
                                double score = item.getScore(); // 加载当前的分数
                                String title = item.getTitle(); // 加载当前的标题

                                totalScore += score; // 加到总分上去

                                // 创建一个新的账单对象
                                Bill bill = new Bill(title, -score, currentDate); // 消费成就点，在账单里显示为负的，并附加当前日期
                                bills.add(bill);
                            }
                        }

                        new weekRewardDataBank().SaveTotalScore(requireActivity(), totalScore); // 存储总分
                        new BillDataBank().saveBills(requireActivity(), bills); // 保存账单列表

                        // 移除已选择的任务并保存
                        weekRewardItems.removeIf(weekRewardItem::isSelected);
                        new weekRewardDataBank().SaveWeekRewardItems(requireActivity(), weekRewardItems); // 保存已更新的列表

                        dayRewardItemAdapter.notifyDataSetChanged(); // 通知适配器数据发生了变化
                        donebutton.setVisibility(View.GONE);
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 无需执行任何操作
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        return rootView;
    }

    public void onDataChanged() {
        // 刷新界面
        if (isAdded()) { // 这将确保当 Fragment 附加到 Activity 时才执行更新操作
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    boolean isAtLeastOneChecked = false;
                    for (weekRewardItem d : weekRewardItems) {
                        if (d.isSelected()) {
                            isAtLeastOneChecked = true;
                            break;
                        }
                    }

                    // 根据是否有条目被选中来显示或隐藏按钮
                    donebutton.setVisibility(isAtLeastOneChecked ? View.VISIBLE : View.GONE);
                }
            });
        }
    }



    ActivityResultLauncher<Intent> addItemLauncher;
    ActivityResultLauncher<Intent> updataItemLauncher;

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getGroupId() != 22) {
            return super.onContextItemSelected(item);
        }
        switch (item.getItemId()) {
            case 0:
                // 创建确认完成的对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("确认完成");
                builder.setMessage("确认完成了吗？");
                // 设置确认按钮的点击事件
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确认按钮，执行完成任务并更新数据
                        weekRewardItem dayRewardItem = weekRewardItems.get(item.getOrder());//获取当前实例


                        double score = dayRewardItem.getScore();//加载当前的分数
                        String title =dayRewardItem.getTitle();//加载当前的名称
                        totalScore += score;//加到总分上去
                        new weekRewardDataBank().SaveTotalScore(requireActivity(), totalScore);//存储


                        // 创建一个新的账单对象
                        // 创建一个新的账单对象，并获取当前日期
                        LocalDate currentDate = LocalDate.now();
                        Bill bill = new Bill(title, -score, currentDate); // 消费成就点，在账单里显示为负的，并附加当前日期
                        // 加入到账单列表中
                        ArrayList<Bill> bills = new BillDataBank().loadBills(requireActivity());
                        bills.add(bill);
                        new BillDataBank().saveBills(requireActivity(), bills);

                        weekRewardItems.remove(item.getOrder());//删除当前实例
                        dayRewardItemAdapter.notifyItemRemoved(item.getOrder());//刷新
                        new weekRewardDataBank().SaveWeekRewardItems(requireActivity(), weekRewardItems);///保存
                    }
                });
                // 设置取消按钮的点击事件
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消按钮，不执行操作
                        // 可以执行其他适当的操作或返回先前的界面
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case 1:
                // 创建确认删除的对话框
                AlertDialog.Builder builder1 = new AlertDialog.Builder(requireActivity());
                builder1.setTitle("确认删除");
                builder1.setMessage("确认删除数据吗？");
                // 设置确认按钮的点击事件
                builder1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        weekRewardItem dayRewardItem = weekRewardItems.get(item.getOrder());//获取当前实例
                        double score = dayRewardItem.getScore();//加载当前的分数

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        double havedScore = new achievementPointDataBank().loadAchievementPoints(requireContext());
                        havedScore+=score;
                        new achievementPointDataBank().saveAchievementPoints(requireActivity(),havedScore);//回收成就点
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        // 用户点击确认按钮，执行删除数据的操作
                        weekRewardItems.remove(item.getOrder());
                        dayRewardItemAdapter.notifyItemRemoved(item.getOrder());
                        new weekRewardDataBank().SaveWeekRewardItems(requireActivity(), weekRewardItems);
                    }
                });
                // 设置取消按钮的点击事件
                builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消按钮，不执行删除数据的操作
                        // 可以执行其他适当的操作或返回先前的界面
                    }
                });
                AlertDialog dialog1 = builder1.create();
                dialog1.show();
                break;
            case 2:
                // 打开编辑详情页面
                Intent intentUpdata = new Intent(requireActivity(), BookItemDetailsActivity.class);
                // 传递相关数据到编辑页面
                weekRewardItem dayRewardItem = weekRewardItems.get(item.getOrder());
                intentUpdata.putExtra("name", dayRewardItem.getTitle());
                intentUpdata.putExtra("score", dayRewardItem.getScore());
                intentUpdata.putExtra("position", item.getOrder());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                double havedScore = new achievementPointDataBank().loadAchievementPoints(requireContext());
                new achievementPointDataBank().saveAchievementPoints(requireActivity(),havedScore+dayRewardItem.getScore());
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                updataItemLauncher.launch(intentUpdata);
                break;
            default:
                return super.onContextItemSelected(item);
        }

        return false;
    }


    public static class DayRewardItemAdapter extends RecyclerView.Adapter<weekRewardFragment.DayRewardItemAdapter.ViewHolder> {

        private final ArrayList<weekRewardItem> localDataSet;
        private ItemTouchHelper itemTouchHelper;
        public DayRewardItemAdapter(ArrayList<weekRewardItem> dataSet) {
            localDataSet = dataSet;
        }

        private OnDataChangeListener onDataChangeListener;
        public void setOnDataChangeListener(OnDataChangeListener onDataChangeListener) {
            this.onDataChangeListener = onDataChangeListener;
        }

        public void setItemTouchHelper(ItemTouchHelper itemTouchHelper) {
            this.itemTouchHelper = itemTouchHelper;
        }

        public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {

            private final TextView textViewName;            //任务名称
            private final TextView textViewScore;

            private final CheckBox checkBox;
            private final ImageView imageView;
            private ItemTouchHelper itemTouchHelper; // 添加一个ItemTouchHelper实例的变量
            public ViewHolder(View view,ItemTouchHelper touchHelper) {
                super(view);
                // Define click listener for the ViewHolder's View

                textViewName = view.findViewById(R.id.reward_item);
                textViewScore = view.findViewById(R.id.awarding_point);
                checkBox = view.findViewById(R.id.checkbox21);
                imageView = view.findViewById(R.id.drag_handle21);
                this.itemTouchHelper = touchHelper; // 设置ItemTouchHelper实例
                imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        // 当imageView被长按时，触发拖动
                        if (itemTouchHelper != null) {
                            itemTouchHelper.startDrag(ViewHolder.this);
                        }
                        return true;
                    }
                });
                view.setOnCreateContextMenuListener(this);

            }


            @Override
            //创建一个显示的菜单
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");
                menu.add(22, 0, this.getAdapterPosition(), "完成");
                menu.add(22, 1, this.getAdapterPosition(), "删除");
                menu.add(22, 2, this.getAdapterPosition(), "修改");
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewScore() {
                return textViewScore;
            }
        }


        @NonNull
        @Override
        public weekRewardFragment.DayRewardItemAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.reward_item_row, viewGroup, false);

            return new weekRewardFragment.DayRewardItemAdapter.ViewHolder(view, itemTouchHelper); // 传递ItemTouchHelper实例
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        //绑定数据和View
        public void onBindViewHolder(weekRewardFragment.DayRewardItemAdapter.ViewHolder viewHolder, final int position) {

            // Get element from your dataset at this position and replace the
            // contents of the view with that element
            viewHolder.getTextViewName().setText(localDataSet.get(position).getTitle());
            viewHolder.getTextViewScore().setText("- "+localDataSet.get(position).getScore());

            weekRewardItem dayRewardItem = localDataSet.get(position);
            viewHolder.checkBox.setOnCheckedChangeListener(null); // 避免重用视图时触发事件
            viewHolder.checkBox.setChecked(dayRewardItem.isSelected());    // 根据当前状态设置复选框
            viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // 更新书本对象的状态
                    dayRewardItem.setSelected(isChecked);
                    new weekRewardDataBank().SaveWeekRewardItems(buttonView.getContext(),localDataSet);
                    // 如果有其他需要在此处处理的逻辑，比如回调，可以在这里实现
                    if (onDataChangeListener != null) {
                        onDataChangeListener.onDataChanged();
                    }

                }
            });

            // 在你设置长按监听的地方

        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return localDataSet.size();
        }
    }
    ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {

        @Override
        public boolean isLongPressDragEnabled() {
            // 禁用长按触发拖动，因为我们会手动控制这个行为
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                              RecyclerView.ViewHolder target) {

            final int fromPosition = viewHolder.getAdapterPosition();
            final int toPosition = target.getAdapterPosition();

            // 对数据集进行操作以交换项的位置
            Collections.swap(weekRewardItems, fromPosition, toPosition);


            // 通知适配器项移动了
            dayRewardItemAdapter.notifyItemMoved(fromPosition, toPosition);

            // 可选的，如果您有关联的数据变化或持久化的逻辑，可以在此处进行处理

            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // 这里处理滑动事件，本例中不需要



        }

        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {


                // 可以在此处创建一个扩散效果
                Drawable background = viewHolder.itemView.getBackground();
                if (background instanceof RippleDrawable) {
                    // 让 Ripple 效果运行
                    RippleDrawable rippleDrawable = (RippleDrawable) background;
                    rippleDrawable.setHotspot(viewHolder.itemView.getWidth() / 2f, viewHolder.itemView.getHeight() / 2f);
                    rippleDrawable.setState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled});
                } else {
                    // 创建并设置一个新的 RippleDrawable
                    ColorStateList rippleColor = ColorStateList.valueOf(Color.WHITE);
                    Drawable contentDrawable = new ColorDrawable(Color.LTGRAY); // 您可以自定义这个为任何你想要的 Drawable
                    RippleDrawable rippleDrawable = new RippleDrawable(rippleColor, contentDrawable, null);
                    viewHolder.itemView.setBackground(rippleDrawable);
                    rippleDrawable.setHotspot(viewHolder.itemView.getWidth() / 2f, viewHolder.itemView.getHeight() / 2f);
                    rippleDrawable.setState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled});
                }
            }
        }

        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);


            // 清除之前设置的背景等
            viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);

        }
    };
}